/**
 * Copyright (c) 2017 hadlinks, All Rights Reserved.
 */
package com.bugull.farm.core.proxy.example;

import com.alibaba.fastjson.JSONObject;
import com.bugull.farm.core.annotation.CmdEventAnnotation;
import com.bugull.farm.core.annotation.LogAnnotation;
import com.bugull.farm.core.control.AbstractBuguEvent;
import com.bugull.farm.core.control.AbstractBuguEventManager;
import com.bugull.farm.core.control.example.CmdResEventManager;
import com.bugull.farm.core.proxy.AbstractHandler;
import com.bugull.farm.core.proxy.AfterHandler;
import com.bugull.farm.core.utils.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Method;

/**
 * Project Name: bugu-farm-household 
 * Package Name: com.bugull.farm.core.proxy.example 
 * ClassName: AfterHandlerImpl 
 * Function: TODO ADD FUNCTION.  
 * date: 2017/11/7 17:22
 * @author songwei (songw@hadlinks.com)
 * @since JDK 1.8 
 */
public class AfterHandlerImpl extends AfterHandler {

    @Override
    public void handleAfter(Object proxy, Method method, Object[] args) {
        //监控命令事件注解，在处理完成后推送通知到各个监听器
        if (method.isAnnotationPresent(CmdEventAnnotation.class)) {
            JSONObject frame = null;
            ChannelHandlerContext ctx = null;
            for (Object arg : args) {
                if (arg instanceof JSONObject) {
                    frame = (JSONObject)arg;
                }
                if (arg instanceof ChannelHandlerContext) {
                    ctx = (ChannelHandlerContext)arg;
                }
            }
            //注解中的附加信息
            String appender = method.getAnnotation(CmdEventAnnotation.class).value();
            AttributeKey<CmdResEventManager> managerAttributeKey = AttributeKey.valueOf("manager");
            Attribute<CmdResEventManager> attr = ctx.channel().attr(managerAttributeKey);
            CmdResEventManager manager = attr.get();
            try {
                //添加了命令事件注解的方法，触发事件推送
                manager.notifyResWithCxt(ctx, frame);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
